package tictactoe.multiplayer.server;

//~--- non-JDK imports --------------------------------------------------------

import tictactoe.Player;

import tictactoe.exceptions.network.NetworkException;
import tictactoe.exceptions.network.PlayerAlreadyInException;
import tictactoe.exceptions.network.PlayerNotInException;

import tictactoe.util.Constants;

//~--- JDK imports ------------------------------------------------------------

import java.util.Collections;
import java.util.Hashtable;
import java.util.Set;

/**
 *
 * @author Home
 */
public class PlayerPoll {
    private Hashtable<Player, ClientHandler> players;

    /**
     *
     */
    public PlayerPoll() {
        players = new Hashtable<Player, ClientHandler>();
    }

    /**
     *
     * @param p
     * @param handler
     * @throws NetworkException
     */
    public synchronized void addPlayer(Player p, ClientHandler handler) throws NetworkException {
        if (players.contains(p)) {
            throw new PlayerAlreadyInException(p.getName() + "already logged");
        }

        players.put(p, handler);
    }

    /**
     *
     * @param p
     * @throws NetworkException
     */
    public synchronized void removePlayer(Player p) throws NetworkException {
        if (!players.containsKey(p)) {
            throw new PlayerNotInException(p.getName() + " not in list");
        }

        players.remove(p);
    }

    /**
     *
     * @return
     */
    public synchronized Set<Player> getPlayers() {
        return Collections.unmodifiableSet(players.keySet());
    }

    /**
     *
     * @param p
     * @return
     * @throws NetworkException
     */
    public synchronized ClientHandler getHandler(Player p) throws NetworkException {
        if (!players.containsKey(p)) {
            throw new PlayerNotInException(p.getName() + " not in list");
        } else {
            return players.get(p);
        }
    }

    /**
     *
     * @return
     */
    public String getPlayersString() {
        Set<Player>   set = getPlayers();
        StringBuilder sb  = new StringBuilder();

        for (Player p : set) {
            if (sb.length() > 0) {
                sb.append(Constants.PLAYER_SEPARATOR);
            }

            sb.append(p.getName());
        }

        return sb.toString();
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
